//
//  VVComposeViewController.swift
//  Weibo
//
//  Created by 王惠平 on 2017/4/5.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit
import SVProgressHUD

class VVComposeViewController: UIViewController {
    
    //懒加载控件
    fileprivate lazy var titleLabel: UILabel = {
    
        let label = UILabel(fonSize: 17, textColor: UIColor.darkGray, text: "")
        
        if let name = VVUserAccountViewModel.sharedViewModel.userAccount?.name {
            
        let message = "发微博\n" + name
            
            //获取名字的范围
            let range = (message as NSString).range(of: name)
            
            //创建富文本
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: message)
            
            //设置name文字的颜色和字体大小
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName:UIColor.orange], range: range)
            
            //需要设置富文本
            label.attributedText = attributedStr
            
            //多行显示
            label.numberOfLines = 0
            
            //居中显示
            label.textAlignment = .center
            
        } else {
            
            //没有登录也就是没有名字
            label.text = "发微博"
        }
    
        label.sizeToFit()
    
    return label
    
    }()
    
    //发送按钮
    fileprivate lazy var sendButton: UIButton = {
        
        let button = UIButton()
        
        //点击事件
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        
        //设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named:"common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        
        //设置文字
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .disabled)
        
        //设置字体大小
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        
        //设置button大小
        button.size = CGSize(width: 45, height: 35)
        
        return button
    }()
    
    //textView
    fileprivate lazy var textView: VVTextView = {
        
       let textView = VVTextView()
        
        textView.delegate = self
        
        textView.placeHolder = "听说下雨天音乐与辣条更配吆~"
        
        textView.font = UIFont.systemFont(ofSize: 14)
        
        textView.textColor = UIColor.darkGray
        
        //textView.text = "sffgh"
        
        //垂直方向可以拖动
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    //TOOlBar
    fileprivate lazy var toolBar: VVComploseToolBar = VVComploseToolBar()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }

    //配图
    fileprivate lazy var pictureView: VVComposePictureView = {
        
       let collectionView = VVComposePictureView()
        
        return collectionView
        
    }()
    
    //表情键盘
    fileprivate lazy var emoticonKeyBoard: VVEmoticonKeyBoard = {
        
       let keyBoard = VVEmoticonKeyBoard()
        
        keyBoard.size = CGSize(width: self.textView.width, height: 216)
        
        return keyBoard
        
    }()
    
    private func setupUI() {
        
        view.backgroundColor = UIColor.cyan
        
        //监听键盘frame的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChangeAction(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //监听表情按钮点击的通知
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectorEmoticonButtonAction(noti:)), name: NSNotification.Name(DidSelectedEmoitconButtonNoti), object: nil)
        
        //监听删除表情的通知
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedDeleteEmotionAction), name:  NSNotification.Name(DidSelectedDeleteEmoticonNoti), object: nil)
        
        setupNAV()
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        view.addSubview(pictureView)
        
        textView.snp.makeConstraints { (make) in
            
            make.top.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(toolBar.snp.top)
        }
        
        toolBar.snp.makeConstraints { (make) in
            
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(35)
     
        }
        
        pictureView.snp.makeConstraints { (make) in
            
            make.top.equalTo(textView).offset(200)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-2 * HomeCellMargin)
            make.height.equalTo(textView.snp.width).offset(-2 * HomeCellMargin)
        }
        
        toolBar.buttonActionClosure = {[weak self] (type: VVComposeToolBarButtonType)->() in

            switch type {
            case .picture:
                
                print("图片")
                
                //图片浏览器
                self?.didSelectedPicture()
                
            case .mention:
                
                print("@")
                
            case .trent:
                
                print("#")
                
            case .emoticon:
                
                print("表情")
                self?.didSelectedEmotion()
                
            case .add:
                
                print("加号")
            
            }
        }
        
        //设置闭包的回调
        pictureView.addPictureClosure = { [weak self] in
            
            self?.didSelectedPicture()
            
        }
    }
    
    //添加导航栏视图
    fileprivate func setupNAV() {
        
        //左侧取消按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        
        //添加富文本视图
        navigationItem.titleView = titleLabel
        
        //右侧发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        //默认右侧按钮不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    //取消按钮监听事件
    @objc private func cancelAction() {
        
        //结束编辑失去第一响应者
        self.view.endEditing(true)
        
        dismiss(animated: true, completion: nil)
    }
   
    //按钮的点击事件
    @objc private func sendAction() {
        
        //获取令牌
        let accessToken = VVUserAccountViewModel.sharedViewModel.accessToken!
        
        //微博内容
        //let content = textView.text!
        
        //获取富文本对应的字符串
        let content = textView.emoticonText
        
        SVProgressHUD.show()
        
        if pictureView.images.count > 0 {
            
            let image = pictureView.images.first!
            
            //有图片
            VVNetworkTools.sharedTools.sendWeiboMessage(accessToken: accessToken, status: content, pic: image, finishCallBack: { (response, error) in
                
                if error != nil {
                    
                    SVProgressHUD.showError(withStatus: "发送失败")
                    
                    print(error ?? 0)
                } else {
                    
                    SVProgressHUD.showSuccess(withStatus: "发送成功")
                }
            })
            
        } else {
            
            //发送文字微博
            VVNetworkTools.sharedTools.sendWeiboMessage(accessToken: accessToken, status: content) { (response, error) in
                
                if error != nil {
                    
                    SVProgressHUD.showError(withStatus: "发送失败")
                } else {
                    
                    SVProgressHUD.showSuccess(withStatus: "发送成功")
                }
                
            }
            
        }

    }
    
    //监听键盘的frame的改变
    @objc private func keyBoardFrameChangeAction(noti: Notification) {
        
        let userinfo = noti.userInfo!
        
        //获取键盘的frame
        let keyBoardFrame = userinfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        //获取键盘的动画时长
        let duration = userinfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        
        //修改toolBar的底部约束
        toolBar.snp.updateConstraints { (make) in
            
            make.bottom.equalTo(self.view).offset(-(ScreenHeight - keyBoardFrame.origin.y))
        }
        
        //添加约束动画
        UIView.animate(withDuration: duration) { 
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    //点击按钮的监听方法
    @objc private func didSelectorEmoticonButtonAction(noti: Notification) {
        
        //获取点击的表情模型
        let emoticon = noti.object as! VVEmoticon
        
        //插入表情富文本
        textView.insertEmoticon(emoticon: emoticon)
        
        //保存点击的表情模型
        VVEmoticonTools.sharedTools.saveRecentEmoticonArray(emoticon: emoticon)

    }
    
    //MARK: ---点击删除表情按钮的通知
    @objc private func didSelectedDeleteEmotionAction() {
        
        //回删内容
        textView.deleteBackward()
        
    }
    
    //析构函数移除通知
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
}


//toolbar按钮点击逻辑处理
extension VVComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    //点击表情处理逻辑
    fileprivate func didSelectedEmotion() {
        
        //完成系统键盘和表情键盘的切换
        if textView.inputView == nil {
            
            //有系统键盘进入表情键盘
            textView.inputView = emoticonKeyBoard
            
            toolBar.switchEmoticonIcon(isEmoticon: true)
            
        } else {
            
            //有表情键盘进入系统键盘
            textView.inputView = nil
            
            toolBar.switchEmoticonIcon(isEmoticon: false)
        }
        
        //设置成第一响应者
        textView.becomeFirstResponder()
        
        //重新加载输入视图
        textView.reloadInputViews()
        
    }
    
    //点击图片处理逻辑
    fileprivate func didSelectedPicture() {
        
        //在ios10,访问相机和相册需要开启权限
        let imagePicture = UIImagePickerController()
        
        //获取图片需要设置代理
        imagePicture.delegate = self
        
        //判断来源
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            
            //真机运行使用相机
            imagePicture.sourceType = .camera
        } else {
            
            //模拟器运行使用图库
            imagePicture.sourceType = .photoLibrary
        }
        
        //拓展
        //判断摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            
            print("前置摄像头可用")
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            
            print("后置摄像头可用")
        }
        
        //  设置编辑图片 (获取编辑的图片,key是UIImagePickerControllerEditedImage)
        //imagePicture.allowsEditing = true
        
        self.present(imagePicture,animated: true,completion: nil)
        
    }
    
        //  MARK: ---UIImagePickerControllerDelegate
        //  实现代理方法UIImagePickerController不会自己dismiss
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //获取原始图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        //根据指定的宽度压缩图片
        let currentImage = scaleImage(scaleWidth: 200, image: image)
        
        //dismiss
        picker.dismiss(animated: true, completion: nil)
        
        //添加显示图片
        pictureView.addImage(image: currentImage)
    }
    
    //根据指定压缩后的宽度计算图片压缩后的大小
    fileprivate func scaleImage(scaleWidth: CGFloat, image: UIImage) ->UIImage {
        
        //根据压缩后的宽度计算压缩后的高度
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        
        //压缩后大小
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        
        //开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        
        //把图片压缩到指定区域内
        image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
        
        //从图片上下文中获取图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()

        //关闭上下文
        UIGraphicsEndImageContext()

        return currentImage!
    }

}

extension VVComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        
        //根据文本框是否有内容判断按钮是否可用
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    //将要拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        //键盘失去第一响应者
        self.view.endEditing(true)
    }
    
}

